<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .v-scroll {
            width: 200px;
            height: 400px;
            overflow: auto;
            border: 1px solid #000;
            margin: 30px 0 0 30px;
        }

        li {
            height: 40px;
            text-align: center;
            line-height: 40px;
            border-bottom: 1px solid #a5a0a0;
            box-sizing: border-box;
        }
    </style>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>

<body>
    <div id="app">
        <div class="v-scroll" ref="scrollRef">
            <ul>
                <li v-for="i in tempData" :key="i">{{i}}</li>
            </ul>
        </div>
    </div>

    <script>
        const { createApp, ref,onMounted,computed } = Vue

        createApp({
            setup() {

                function getAllData() {
                    let data = []
                    for (let i = 0; i < 10000; i++) {
                        data.push(i)
                    }
                    return data
                }

                const allData = ref(getAllData()) //获取到所有的数据
                const scrollRef = ref(null)
                const boxHeight= ref(0)//可视区域的高度
                const itemHeight = ref(40)//每个li的高度
                const itemNum = ref(0)//可视区域可以展示的数据量
                const startIndex =computed(()=>{
                    let index = Math.floor((allData.value.length - 1) / itemNum.value) * itemNum.value
                    if(index<=0){
                        index=0
                    }
                    return index  //起始下标
                })  //起始下标
                const endIndex = computed(()=>{
                    let index = startIndex.value + itemNum.value *2
                    if(!allData.value[index]){
                        index = allData.value.length - 1
                    }
                    return index
                })   //结束下标
                //获取可视区域的高度
                onMounted(()=>{
                    boxHeight.value = scrollRef.value.clientHeight
                    itemNum.value = Math.ceil(boxHeight.value/itemHeight.value)
                   
                })

                const tempData = computed(()=>{//被展示的数组
                    let index = 0
                    if(startIndex.value<= itemNum.value){
                        index=0
                    }else{
                        index = startIndex.value - itemNum.value
                    }
                    return allData.value.slice(index,endIndex.value)
                }) 
                return {
                    allData,
                scrollRef,
                tempData
                }
            }
        }).mount('#app')
    </script>
</body>

</html>